package com.example.lib_base.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
/*
* 不合适 应该还需要添加binding的生命周期相关
*   还涉及到binding获取的视图可能为空的问题 一般发生在屏幕旋转
* */
abstract class BasePagingBindingAdapter<T : Any,B : ViewDataBinding> (private var diffCallback: DiffUtil.ItemCallback<T>) :
    PagingDataAdapter<T, RecyclerView.ViewHolder>(diffCallback){

    private var mItemClickListener:ItemClickListener? =null

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val item = getItem(position) ?: return
        (holder as BasePagingBindingAdapter<*,*>.BaseViewHolder).bindNormalData(item)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val binding  = DataBindingUtil.bind<B>(LayoutInflater.from(parent.context).inflate(viewType,parent,false))
        val holder = binding?.let { BaseViewHolder(it) }
        //Item的点击事件
        holder?.itemView?.setOnClickListener { view ->
            //            onItemClick(getItem(holder.layoutPosition))
            mItemClickListener?.let {
                mItemClickListener!!.itemClick(holder.layoutPosition )
            }
        }
        return holder as RecyclerView.ViewHolder
    }

    override fun getItemViewType(@LayoutRes position: Int): Int {
        return getItemLayout(position)
    }

    /**
     * 子类获取layout
     */
    protected abstract fun getItemLayout(position: Int): Int

    /**
     * itemView的点击事件
     */
    open fun setOnItemClick(listener: ItemClickListener){
        this.mItemClickListener = listener
    }

    /**
     * 子类绑定数据
     */
    protected abstract fun bindData(binding: B?, data: T?)

    inner class BaseViewHolder(var binding: ViewDataBinding) : RecyclerView.ViewHolder(
        binding.root
    ) {
        fun bindNormalData(item: Any?) {
            bindData(binding as B, item as T)
        }
    }

}